package controller

import (
	"ez/apps/mes/auto/controller"
	mes "ez/apps/mes/document"
	"ez/apps/mes/servcie"
	"ez/config/code"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"strings"
)

type FlowController struct {
	controller.FlowAutoController
}

func init() {
	c := &FlowController{}
	c.SetRouteParam("/mes", "/admin", "Flow")
	ez.CreateApi(c.AdminGet(), c.GetAction).SetRouterName("[mes]跟踪单_创建")
	ez.CreateApi(c.AdminList(), c.ListAction).SetRouterName("[mes]跟踪单_列表")
	ez.CreateApi(c.AdminSave(), c.SaveAction).SetRouterName("[mes]跟踪单_保存")
	ez.CreateApi(c.AdminCopy(), c.CopyAction).SetRouterName("[mes]跟踪单_复制")
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction).SetRouterName("[mes]跟踪单_更新")
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction).SetRouterName("[mes]跟踪单_选项")
	ez.CreateApi(c.AdminDelete(), c.DeleteAction).SetRouterName("[mes]跟踪单_删除")
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction).SetRouterName("[mes]跟踪单_恢复")
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction).SetRouterName("[mes]跟踪单_销毁")
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction).SetRouterName("[mes]跟踪单_更新_批量")
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction).SetRouterName("[mes]跟踪单_删除_批量")
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction).SetRouterName("[mes]跟踪单_销毁_批量")
	ez.CreateApi(c.AdminModelApi("check_and_start"), c.CheckAndStartAction).SetRouterName("[mes]跟踪单_创建/获取跟踪单")
	ez.CreateApi(c.AdminModelApi("get_check_tags"), c.GetCheckTagsAction).SetRouterName("[mes]跟踪单_获取检验项目")
	ez.CreateApi(c.AdminModelApi("check_save"), c.CheckSaveAction).SetRouterName("[mes]跟踪单_保存检验单")
}

// func (c FlowController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c FlowController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c FlowController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
func (c FlowController) GetCheckTagsAction(session *ez.Session) {
	this := cc.New(session)
	sn := this.Get("code").IsString()
	strTmp := strings.Split(sn, ".")
	if len(strTmp) == 0 {
		this.ReturnError(code.Error, "跟踪单号有误", "")
		return
	}

	//获取计划
	qrCode := servcie.NewQrCode(sn)
	plan := qrCode.GetPlan()
	if plan.Id == 0 {
		this.ReturnError(code.Error, "计划未找到", "")
		return
	}
	plan.LoadTemplate()
	if plan.Template.Id == 0 {
		this.ReturnError(code.Error, "计划模板未找到", "")
		return
	}
	plan.Template.LoadChecks()
	if plan.Template.Checks == nil || len(plan.Template.Checks) == 0 {
		this.ReturnError(code.Error, "计划模板无检验项目", "")
		return
	}
	//todo 目前只使用第一个模板作为检验项目
	checkTemplate := plan.Template.Checks[0]
	checkGroups, _ := mes.NewCheckResultGroupCrud().FindBy(ss.M{}, []string{"id"}, 0, 0)
	checkTagCrud := mes.NewCheckTagCrud()
	re := make([]ss.M, 0)
	for _, checkGroup := range checkGroups {
		group := ss.M{
			"id":   checkGroup.Id,
			"name": checkGroup.Name,
			"tags": make([]ss.M, 0),
		}
		tags, _ := checkTagCrud.FindBy(ss.M{
			"groupId":   checkGroup.Id,
			"processId": checkTemplate.ProcessId,
		}, []string{}, 0, 0)

		for _, tag := range tags {
			tagItem := ss.M{
				"id":    tag.Id,
				"name":  tag.Name,
				"value": nil,
			}
			group["tags"] = append(group["tags"].([]ss.M), tagItem)
		}
		re = append(re, group)
	}
	this.ReturnSuccess("OK", re)
}

func (c FlowController) CheckAndStartAction(session *ez.Session) {
	this := cc.New(session)
	code := this.Get("code").IsString()

	helper := servcie.NewQrCode(code)

	//获取跟踪单
	flow := helper.GetFlowOrCreateEmpty()

	this.ReturnSuccess("OK", flow)
}

type checkSaveQuery struct {
	Code         string `json:"code"`
	Emp          int64  `json:"emp"`
	CheckProcess int64  `json:"checkProcess"`
	Groups       []struct {
		Id   int64 `json:"id"`
		Tags []struct {
			Id    int64   `json:"id"`
			Value float64 `json:"value"`
		} `json:"tags"`
	} `json:"groups"`
}

func (c FlowController) CheckSaveAction(session *ez.Session) {
	this := cc.New(session)
	query := new(checkSaveQuery)

	if this.Try(this.FillJson(query)) {
		return
	}
	//创建检验单
	check := new(mes.Check)
	check.EmpId = query.Emp
	check.ProcessId = query.CheckProcess

	//--通过跟踪单号获取跟踪单ID
	flow, _ := mes.NewFlowCrud().FindOneBy(ss.M{"sn": query.Code}, nil)
	if flow.Id == 0 {
		this.ReturnError(code.Error, "跟踪单未找到", "")
		return
	}
	check.FlowId = flow.Id
	_ = check.Save()

	//--写入检验结果
	for _, group := range query.Groups {
		for _, tag := range group.Tags {
			result := new(mes.CheckResult)
			result.GroupId = group.Id
			result.TagId = tag.Id
			result.Num = tag.Value
			result.CheckId = check.Id
			_ = result.Save()
		}
	}
	check.Factory.TriggerAfterUpdate(check)

	this.ReturnSuccess("OK", "保存成功")
}
